package com.gcloud.mesh.monitor.service;

import java.text.SimpleDateFormat;
import java.util.*;

import com.gcloud.mesh.dcs.dao.AliPowerDao;
import com.gcloud.mesh.dcs.entity.AliPowerEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.asset.service.IAssetService;
import com.gcloud.mesh.asset.service.ICloudResourceService;
import com.gcloud.mesh.dcs.service.AppService;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.enums.MonitorMeter;
import com.gcloud.mesh.header.msg.monitor.StatisticsMsg;
import com.gcloud.mesh.header.vo.asset.CloudResourceItemVo;
import com.gcloud.mesh.header.vo.asset.DatacenterItemVo;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.header.vo.asset.NodeItemVo;
import com.gcloud.mesh.header.vo.dcs.AppVo;
import com.gcloud.mesh.header.vo.monitor.MeterVo;
import com.gcloud.mesh.header.vo.monitor.SampleVo;
import com.gcloud.mesh.header.vo.monitor.StatisticsPointVo;
import com.gcloud.mesh.header.vo.monitor.StatisticsResourceVo;
import com.gcloud.mesh.header.vo.monitor.StatisticsVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;
import com.gcloud.mesh.monitor.util.HttpClientUtil;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.GcePageReply;
import com.gcloud.mesh.sdk.gce.PodVo;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.enums.K8sClusterType;
import com.gcloud.mesh.supplier.enums.SystemType;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class StatisticsService {

	@Autowired
	private IAssetService assetService;

	@Autowired
	private ICloudResourceService cloudResourceService;

	@Autowired
	private AppService appService;

	@Autowired
	private StatisticsCheatService cheatService;

	@Autowired
	private SupplierDao supplierDao;

	@Autowired
	private AliPowerDao aliPowerDao;

	@Autowired
	private StatisticsDao statisticsDao;

	private static final SimpleDateFormat monitorSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	private static final String HTTP = "http://";

	private static final String monitorPort = "9090";

	private static final String statisticsUrl = "/monitor/Statistics";

	private static final String latestSampleUrl = "/monitor/LatestSample";

	private static final String latestSamplesUrl = "/monitor/LatestSamples";

	private static final String listMultiSampleUrl = "/monitor/ListMultiSample";

	public List<MeterVo> listMeter() {
		List<MeterVo> meters = new ArrayList<MeterVo>();

		for (MonitorMeter meter : MonitorMeter.values()) {
			if (meter.getMeter().startsWith("cost") || meter.getType().startsWith("datacenter")
					|| meter.getMeter().contains("cores") || meter.getMeter().contains("cpu_L2cache")
					|| meter.getMeter().contains("mem_total") || meter.getMeter().contains("storage_total")
					|| meter.getMeter().contains("bandWidth")) {
				continue;
			}

			MeterVo vo = new MeterVo();

			vo.setMeter(meter.getMeter());
			vo.setChnName(meter.getName());
			vo.setResourceType(meter.getType());
			vo.setUnit(meter.getUnit());
			meters.add(vo);
		}

		return meters;

	}

	public StatisticsVo statistics(StatisticsMsg msg) {

		Map<String, Object> params = new HashMap<>();

		String meter = msg.getMeter();

		String datacenterId = "";
		if (meter.startsWith("server") || meter.startsWith("host") || meter.startsWith("switcher")) {
			DeviceItemVo device = assetService.detailDevice(msg.getResourceId(), "");
			if (device.getType().equals(DeviceType.SERVER.getNo())) {
				NodeItemVo node = assetService.detailNode(msg.getResourceId(), "");
				String hostname = node.getHostname();
				if (msg.getMeter().startsWith("server")) {
					params.put("resourceId", hostname);
				} else {
					params.put("host", hostname);
				}
			} else {
				params.put("resourceId", device.getDeviceId());
			}
			datacenterId = device.getDatacenterId();
		} else if (meter.startsWith("datacenter") || meter.startsWith("environment")) {
			datacenterId = msg.getResourceId();
		}

		// 固定参数
		params.put("interval", "1m");
		params.put("platformType", 3);
		params.put("regionId", "regionA");

		// 查询参数
		params.put("meter", msg.getMeter());
		params.put("beginTime", msg.getBeginTime());
		params.put("endTime", msg.getEndTime());

		// 获取数据中心ip
		DatacenterItemVo dcVo = assetService.detailDatacenter(datacenterId, "");
		String url = HTTP + dcVo.getIp() + ":" + monitorPort + statisticsUrl;

		String result = HttpClientUtil.doGet(url, params);

		if (result != null) {
			JSONObject json = JSONObject.fromObject(result);
			Map<String, Class> classMap = new HashMap<String, Class>();
			classMap.put("list", StatisticsResourceVo.class);
			classMap.put("points", StatisticsPointVo.class);
			StatisticsVo data = (StatisticsVo) JSONObject.toBean(json.getJSONObject("data"), StatisticsVo.class,
					classMap);
			return data;
		}

		return cheatService.statistics(msg);
	}

	public String latestSample(String meter, String resourceId) {

		String datacenterId = "";
		Map<String, Object> params = new HashMap<>();

		params.put("meter", meter);

		// if (meter.startsWith("container")) {
		// AppVo app = appService.checkAndGet(resourceId);
		// datacenterId = app.getCloudResourceId();
		// String namespaceId = app.getId();
		// String clusterId =
		// supplierDao.getConfigValueByDatacenterIdAndConfigName(app.getCloudResourceId(),
		// SystemType.K8S.getName(), K8sClusterType.CLUSTER_ID.getName());
		//
		// GceSDK sdk = SpringUtil.getBean(GceSDK.class);
		// GcePageReply<PodVo> vos = sdk.pagePod(clusterId, namespaceId, 1,
		// 999);
		// for (PodVo vo : vos.getData()) {
		// params.put("resourceId", vo.getName());
		// }
		// params.put("platformType", 3);
		// params.put("regionId", "regionA");
		// }
		if (meter.startsWith("server") || meter.startsWith("host") || meter.startsWith("switcher")) {
			DeviceItemVo device = assetService.detailDevice(resourceId, "");
			if (device != null) {
				datacenterId = device.getDatacenterId();
				if (device.getType().equals(DeviceType.SERVER.getNo())) {
					NodeItemVo node = assetService.detailNode(resourceId, "");
					String hostname = node.getHostname();
					if (meter.startsWith("server")) {
						params.put("resourceId", hostname);
					} else {
						params.put("host", hostname);
					}
					params.put("platformType", 3);
					params.put("regionId", "regionA");
				} else {
					params.put("resourceId", device.getDeviceId());
				}
			}
		} else if (meter.startsWith("datacenter") || meter.startsWith("environment")) {
			datacenterId = resourceId;
			params.put("resourceId", resourceId);
		} else if (meter.startsWith("container")) {
			AppVo app = appService.checkAndGet(resourceId);
			datacenterId = app.getDatacenterId();
		} else if (meter.startsWith("vm") || meter.startsWith("k8s")) {
			CloudResourceItemVo cs = cloudResourceService.detail(resourceId);
			datacenterId = cs.getDatacenterId();
		}

		params.put("platformType", 3);
		params.put("regionId", "regionA");

		// 获取数据中心ip
		DatacenterItemVo dcVo = assetService.detailDatacenter(datacenterId, "");
		String url = HTTP + dcVo.getIp() + ":" + monitorPort + latestSampleUrl;

		String result = HttpClientUtil.doGet(url, params);
		if (result != null) {
			JSONObject json = JSONObject.fromObject(result);
			JSONObject data = json.getJSONObject("data");
			if (data.containsKey("list")) {
				JSONObject list = data.getJSONObject("list");
				if (list.containsKey("volume")) {
					String volume = list.get("volume").toString();
					return volume;
				}
			}
		}

		return cheatService.latestSample(meter, resourceId);
	}

	public List<SampleVo> latestSamples(String meter, String resourceId) {

		Map<String, Object> params = new HashMap<>();

		params.put("meter", meter);
		params.put("platformType", 3);
		params.put("regionId", "regionA");

		DeviceItemVo device = assetService.detailDevice(resourceId, "");

		if (device.getType() != null && device.getType().equals(DeviceType.SERVER.getNo())) {
			NodeItemVo node = assetService.detailNode(resourceId, "");
			String hostname = node.getHostname();
			if (meter.startsWith("server")) {
				params.put("resourceId", hostname);
			} else {
				params.put("host", hostname);
			}
		} else if (device.getDeviceId() != null) {
			params.put("resourceId", device.getDeviceId());
		} else {
			params.put("resourceId", resourceId);
		}

		String datacenterId = "";
		if (meter.startsWith("datacenter") || meter.startsWith("environment")) {
			datacenterId = resourceId;
		} else {
			datacenterId = device.getDatacenterId();
		}
		// 获取数据中心ip
		DatacenterItemVo dcVo = assetService.detailDatacenter(datacenterId, "");
		String url = HTTP + dcVo.getIp() + ":" + monitorPort + latestSamplesUrl;

		List<SampleVo> samples = new ArrayList<SampleVo>();

		String result = HttpClientUtil.doGet(url, params);
		if (result != null) {
			JSONObject json = JSONObject.fromObject(result);
			JSONObject data = json.getJSONObject("data");
			JSONArray list = data.getJSONArray("list");
			if (list.size() > 0) {
				for (int i = 0; i < list.size(); i++) {
					SampleVo sample = new SampleVo();
					JSONObject series = list.getJSONObject(i);
					sample.setMeter(series.getString("meter"));
					sample.setVolume(series.getDouble("volume"));
					sample.setUnit(series.getString("unit"));

					samples.add(sample);
				}
			}
		}
		return cheatService.latestSamples(meter, resourceId);
	}

	public String latestSampleFromDb(String meter, String resourceId) {
		StatisticsEntity latestSample = statisticsDao.getLastData(meter, resourceId);
		if (latestSample != null) {
			Date date = new Date();
			//取一分钟以内的
			if(date.getTime() - latestSample.getTimestamp().getTime() < 120*1000) {
				return latestSample.getValue().toString();
			}else {
				return "";
			}
			
		}
		return "";
	}

	public List<SampleVo> latestSamplesFromDb(String meter, String resourceId) {
		List<SampleVo> res = new ArrayList<SampleVo>();

		List<MonitorMeter> meters = MonitorMeter.getTypeByName(meter);
		for (MonitorMeter type : meters) {
			SampleVo vo = new SampleVo();

			StatisticsEntity latestSample = statisticsDao.getLastData(type.getMeter(), resourceId);

			if (latestSample != null) {
				vo.setVolume(latestSample.getValue());
				vo.setMeter(type.getMeter());
				vo.setUnit(type.getUnit());
			}

			res.add(vo);
		}

		return res;
	}

}
